const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('getGoods 云函数被调用，参数：', event)
  
  try {
    const { 
      recommended = null, 
      category = null,
      limit = 20, 
      skip = 0, 
      orderBy = 'createdAt', 
      orderType = 'desc' 
    } = event

    // 构建基础查询条件 - 只获取上架商品 (status = 1)
    let whereCondition = {
      status: 1  // 确保只获取上架商品
    }
    
    // 根据推荐状态筛选
    if (recommended !== null && recommended !== undefined) {
      whereCondition.recommended = recommended
    }
    
    // 根据分类筛选
    if (category && category !== 'all') {
      whereCondition.category = category
    }

    console.log('查询条件：', whereCondition)

    // 构建查询
    let query = db.collection('goods').where(whereCondition)
    
    // 排序
    const orderDirection = orderType === 'desc' ? 'desc' : 'asc'
    query = query.orderBy(orderBy, orderDirection)
    
    // 分页
    query = query.skip(skip).limit(limit)
    
    // 执行查询
    const result = await query.get()
    
    console.log(`查询成功，共获取到 ${result.data.length} 个商品`)
    
    return {
      success: true,
      data: result.data,
      total: result.data.length,
      message: '商品数据获取成功'
    }
    
  } catch (error) {
    console.error('getGoods 云函数执行失败：', error)
    return {
      success: false,
      data: [],
      total: 0,
      message: '商品数据获取失败',
      error: error.message
    }
  }
}